package org.dromara.comm_lhz.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.ObjectUtils;
import org.dromara.comm_lhz.entity.AsSearchHistoryEntity;
import org.dromara.comm_lhz.entity.SysMenu;
import org.dromara.comm_lhz.entity.dto.MenuDto;
import org.dromara.comm_lhz.entity.vo.MenuVO;
import org.dromara.comm_lhz.mapper.MenuMapper;
import org.dromara.comm_lhz.service.AsSearchHistoryService;
import org.dromara.comm_lhz.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 菜单服务实现类
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, SysMenu> implements MenuService {

    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private AsSearchHistoryService asSearchHistoryService;


    /**
     * 全局搜索菜单
     *
     * @param menuDto 菜单搜索条件
     * @return 搜索结果列表
     */
    @Override
    public List<MenuVO> globalSearch(MenuDto menuDto) {
        //判断菜单搜索条件是否为空
        if (!Objects.isNull(menuDto)){
            LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();

            // 添加查询条件，搜索菜单名称包含关键词的记录
            queryWrapper.like(SysMenu::getMenuName, menuDto.getMenuName());

            // 添加搜索历史
            AsSearchHistoryEntity asSearchHistoryEntity  = new AsSearchHistoryEntity();
            asSearchHistoryEntity.setSearchHistory(menuDto.getMenuName());
            asSearchHistoryService.addSearchHistory(asSearchHistoryEntity);

            // 使用SysMenu实体执行查询
            List<SysMenu> sysMenuList = menuMapper.selectList(queryWrapper);

            // 将SysMenu转换为MenuVO
            List<MenuVO> menuVOList = sysMenuList.stream()
                .map(this::convertToMenuVO)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

            return menuVOList;
        }else {
            return null;
        }


    }



    /**
     * 将SysMenu实体转换为MenuVO视图对象
     *
     * @param sysMenu SysMenu实体
     * @return 转换后的MenuVO对象
     */
    private MenuVO convertToMenuVO(SysMenu sysMenu) {
        MenuVO menuVO = new MenuVO();
        // 判断字段是否为空
        if (Objects.isNull(sysMenu.getMenuId())|| Objects.isNull(sysMenu.getMenuName()) ||Objects.isNull(sysMenu.getComponent()) ) {
            return null; // 返回null表示该对象不应该被展示
        }
        if (sysMenu.getMenuId() <= 1164800){
            return null;
        }
        // 将sysMenu的属性映射到menuVO中
        menuVO.setMenuId(sysMenu.getMenuId());
        menuVO.setMenuName(sysMenu.getMenuName());
        menuVO.setComponent(sysMenu.getComponent());
        // 如果有其他属性，也需要一一设置
        return menuVO;
    }


}

